import tkinter as tk
import pywinauto
import tkinter.messagebox as messagebox
from time import sleep, time
from threading import Timer
import random, json, pyperclip, os, pyautogui, win32gui, win32con

class StartWowClientController:
  def __init__(self, tk_root) -> None:
    self.tk_root = tk_root
    self.battle_handle = 0
    self.build_ui()
    self.wow_handle = 0
    self.setting_data = None
    self.timer = None

  def build_ui(self):
    tk.Button(self.tk_root, text="启动Task", command=self.run_task).place(x=10, y=50, width=80, height=30)
    tk.Button(self.tk_root, text="调试", command=self.debug).place(x=100, y=50, width=80, height=30)

  def load_settings(self):
    setting_json_path = os.path.join(os.getcwd(), "settings.json")
    setting_data = None
    with open(setting_json_path, "r") as settings_file:
      setting_data = json.load(settings_file)
    return setting_data

  def focus_photo(self):
    # hd = win32gui.FindWindow(None, "Microsoft Edge")
    # print("hd %d", hd)
    # win32gui.SetForegroundWindow(hd)
    hd = pywinauto.findwindows.find_windows(title_re='WOW_Images')[0]
    # win32gui.ShowWindow(hd, win32con.SW_RESTORE)
    win32gui.SetForegroundWindow(hd)
    sleep(1)
    enter_wow_pos = self.get_image_pos(self.setting_data["enter_image"], confidence=self.setting_data['confidence'])
    print(enter_wow_pos.x, enter_wow_pos.y)
    matched = pyautogui.pixelMatchesColor(
      x=int(enter_wow_pos.x), 
      y=int(enter_wow_pos.y),
      expectedRGBColor=(100, 0, 0),
      tolerance=20
    )
    color = pyautogui.pixel(x=int(enter_wow_pos.x), y=int(enter_wow_pos.y))
    print('color:{}'.format(color))
    print('matched:{}'.format(matched))
    # win32gui.EnumWindows()

  def debug_role_ready(self):
    hd = pywinauto.findwindows.find_windows(title_re='魔兽世界')[0]
    # win32gui.ShowWindow(hd, win32con.SW_RESTORE)
    win32gui.SetForegroundWindow(hd)
    sleep(2)
    role_ready_pos = None
    while role_ready_pos is None:
      sleep(1)
      role_ready_pos = self.get_image_pos(
        self.setting_data["role_ready_pos_image"], 
        confidence=self.setting_data["confidence"]
      )
    print("role_ready_pos", role_ready_pos)
  
  def debug_search_role(self):
    hd = pywinauto.findwindows.find_windows(title_re='魔兽世界')[0]
    # win32gui.ShowWindow(hd, win32con.SW_RESTORE)
    win32gui.SetForegroundWindow(hd)
    search_role_btn_pos = None
    while search_role_btn_pos is None:
      sleep(1)
      # search_role_btn_pos = self.get_image_pos("images/search_role.png", confidence=0.8)
      search_role_btn_pos = self.get_image_pos("images/search_role.png", confidence=0.8)
    print("search_role_btn_pos", search_role_btn_pos)
    pyautogui.click(search_role_btn_pos)
    sleep(2)
    pyperclip.copy("李乄白")
    sleep(1)
    pyautogui.hotkey('ctrl','v')
    sleep(1)
    pyautogui.doubleClick(x=search_role_btn_pos.x, y=search_role_btn_pos.y + 60)

  def debug_timer(self):
    print("debug_timer", time())
    self.timer = Timer(1, self.debug_timer)
    self.timer.start()

  def debug_timer1(self):
    print("debug_timer1", time())
    self.timer1 = Timer(1, self.debug_timer1)
    self.timer1.start()

  def get_wow_start_pos(self):
    pos = self.get_image_pos("images/wow_start_img.png", confidence=0.8)
    print(pos)
    if pos is None:
      messagebox.showerror("Error", "Not Find Start Icon.")
      return

  def debug(self):
    self.setting_data = self.load_settings()
    print("setting_data", self.setting_data)
    self.debug_timer()
    self.debug_timer1()
    return
    self.focus_wow_handle()
    sleep(1)
    # pos = self.get_image_pos("images/enter_success.png", confidence=0.2)
    # pos = self.get_image_pos("images/enter_success.png", confidence=0.8)
    # pos = self.get_image_pos("images/enter_wow.png")
    enter_wow_pos = self.get_image_pos("images/enter_wow_02.png", confidence=0.8)
    pyautogui.moveTo(enter_wow_pos.x, enter_wow_pos.y)
    print(enter_wow_pos)

  def run_task(self):
    self.setting_data = self.load_settings()
    self.start_wow_cleint()
    self.login_role()

  def start_wow_cleint(self):
    self.close_older_client()
    self.focus_battle_client()
    if not self.is_battle_avialble():
      return
    sleep(2)
    pos = self.get_image_pos("images/wow_start_img.png", confidence=0.8)
    print(pos)
    if pos is None:
      messagebox.showerror("Error", "Not Find Start Icon.")
      return
    pyautogui.click(pos.x, pos.y)
    enter_logo_pos = None
    while enter_logo_pos is None:
      sleep(1)
      enter_logo_pos = self.get_image_pos("images/wow_enter_logo.png", confidence=0.8)
    self.focus_wow_handle()
    pyautogui.moveTo(x=enter_logo_pos.x, y=enter_logo_pos.y, duration=0.2)
    # messagebox.showinfo("Success", "enter_logo_pos x={}, y={}".format(enter_logo_pos.x, enter_logo_pos.y))
    # return
    enter_wow_pos = None
    while enter_wow_pos is None:
      sleep(1)
      enter_wow_pos = self.get_image_pos("images/enter_wow_02.png", confidence=0.8)

    print(enter_wow_pos.x, enter_wow_pos.y)
    wow_enter_btn_color_matched = False
    while not wow_enter_btn_color_matched:
      sleep(1)
      print("color:{}".format(pyautogui.pixel(x=int(enter_wow_pos.x), y=int(enter_wow_pos.y))))
      wow_enter_btn_color_matched = pyautogui.pixelMatchesColor(
        x=int(enter_wow_pos.x), 
        y=int(enter_wow_pos.y),
        expectedRGBColor=(100, 0, 0),
        tolerance=20
      )
    print("WOW Client Ready!!!")

  def login_role(self, role_name):
    sleep(1)
    search_role_btn_pos = None
    while search_role_btn_pos is None:
      sleep(1)
      # search_role_btn_pos = self.get_image_pos("images/search_role.png", confidence=0.8)
      search_role_btn_pos = self.get_image_pos("images/search_role.png", confidence=0.8)
    print("search_role_btn_pos", search_role_btn_pos)
    pyautogui.click(search_role_btn_pos)
    sleep(2)
    pyperclip.copy(role_name)
    sleep(1)
    pyautogui.hotkey('ctrl','v')
    sleep(5)
    next_pos_x = search_role_btn_pos.x
    next_pos_y = search_role_btn_pos.y + 60
    pyautogui.move(next_pos_x, next_pos_y, duration=0.5)
    sleep(1)
    pyautogui.click(x=next_pos_x, y=next_pos_y)
    sleep(2)
    pyautogui.click(x=next_pos_x, y=next_pos_y, clicks=2, interval=0.1)
    role_ready_pos = None
    while role_ready_pos is None:
      sleep(1)
      role_ready_pos = self.get_image_pos("images/enter_success_01.png", confidence=0.8)
    print("WOW Role Ready.")
    # messagebox.showinfo("Success", "WOW Role Ready.")
  
  def run_wow_task(self):
    pass
  def get_image_pos(self, image,  **kwargs):
    print("get image pos %s", image)
    pos = None
    try:
      pos = pyautogui.locateCenterOnScreen(image,  **kwargs)
    except Exception as e:
      print(e)
    return pos

  def is_battle_avialble(self):
    return self.battle_handle > 0

  def is_wow_avialble(self):
    return self.wow_handle > 0

  def close_older_client(self):
    wow_handle = win32gui.FindWindow(None, '魔兽世界')
    if wow_handle:
      sleep(1)
      win32gui.PostMessage(wow_handle, win32con.WM_CLOSE, 0, 0)

  def focus_wow_handle(self):
    wow_handle = win32gui.FindWindow(None, '魔兽世界')
    win32gui.SetForegroundWindow(wow_handle)

  def focus_battle_client(self):
    self.battle_handle = win32gui.FindWindow(None, '战网')
    if not self.is_battle_avialble():
      messagebox.showerror("Error", "Battle Client Not Start.")
      return
    # if win32gui.IsIconic(self.battle_handle):
      
    # Version:0.9 StartHTML:0000000105 EndHTML:0000000756 StartFragment:0000000141 EndFragment:0000000720
    # win32gui.ShowWindow(self.battle_handle, win32con.SW_MAXIMIZE)
    # 还原窗口
    win32gui.ShowWindow(self.battle_handle, win32con.SW_RESTORE)
    win32gui.SetForegroundWindow(self.battle_handle)